<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item :label="$t('category-name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('please-input',[$t('category-name')])"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('good.category.display-name')" prop="displayName">
        <el-input
          v-model="queryParams.displayName"
          :placeholder="$t('please-input',[$t('good.category.display-name')])"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('whether-to-enable')" prop="enable">
        <dict-select dict-type="boolean_value" v-model="queryParams.enable"
                     :placeholder="$t('please-select',[$t('whether-to-enable')])"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('reset') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dict:add']"
        >{{ $t('add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dict:remove']"
        >{{ $t('delete') }}
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading"
              :data="categoryList"
              row-key="id"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column :label="$t('category-name')" align="center" prop="name" width="200"/>
      <el-table-column :label="$t('good.category.display-name')" align="center" prop="displayName"  width="200"/>
      <el-table-column :label="$t('good.category.postage')" align="center" prop="postage"  width="120"/>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <oss-image-preview v-if="scope.row.image" :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('whether-to-enable')" align="center" prop="enable">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            :active-value="1"
            :inactive-value="0"
            @change="enableChange(scope.row.id)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" prop="enable"  width="180">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="$router.push(`/good/category/${scope.row.id}`)"
            v-if="scope.row.level == 1">
            子分类
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']"
          >{{ $t('edit') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改分类信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item :label="$t('category-name')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('please-select',[$t('category-name')])"/>
        </el-form-item>
        <el-form-item :label="$t('good.category.display-name')" prop="displayName">
          <el-input v-model="form.displayName" placeholder="请输入展示名称"/>
        </el-form-item>
        <el-form-item label="邮费" prop="postage">
          <el-input v-model="form.postage" placeholder="请输入邮费"/>
        </el-form-item>

        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item :label="$t('whether-to-enable')" prop="enable">
          <dict-select dict-type="boolean_value"
                       v-model="form.enable"
                       type="radio"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('ok') }}</el-button>
        <el-button @click="cancel">{{ $t('cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCategory, delCategory, enable, listCategory, updateCategory } from '@/api/good/category'
import DictSelect from "@/components/DictSelect/index.vue";
import OssImagePreview from "@/components/ImagePreview/oss-image-preview.vue";
import RemoteSelect from "@/components/RemoteSelect/index.vue";
import {deepClone, param} from "@/utils";

export default {
  name: "Category",
  dicts: ['boolean_value'],
  components: {RemoteSelect, OssImagePreview, DictSelect},
  data() {
    const parentId = this.$yun.v(this.$route.params, 'id')
    const isLevel2 = this.$yun.v(this.$route.params, 'id') != null
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类信息表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        level: isLevel2 ? 2 : 1,
        page: 1,
        pageSize: 10,
        name: null,
        displayName: null,
        enable: null,
        parentId
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: this.$t('can-not-empty', [this.$t('category-name')]), trigger: "blur"}
        ],
        displayName: [
          {required: true, message: this.$t('can-not-empty', [this.$t('good.category.display-name')]), trigger: "blur"}
        ],
        postage: [
          {required: true, message: '邮费不能为空',trigger: "blur"}
        ],
        image: [
          {required: false, message: this.$t('please-upload', [this.$t('img')]), trigger: "change"}
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    param,
    /** 查询分类信息列表 */
    getList() {
      const data = deepClone(this.queryParams)
      delete data['pageSize']
      delete data['page']
      listCategory(
        {
          size: this.queryParams.pageSize, current: this.queryParams.page,
          records: [data]
        }
      ).then(response => {
        this.categoryList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        name: null,
        displayName: null,
        image: null,
        unselectedImage: null,
        selectedImage: null,
        level: null,
        blockBuyerPlatform: null,
        enable: '1',
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分类信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {...row};
      this.open = true;
      this.title = this.$t('edit') + "分类信息";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.parentId = this.queryParams.parentId
          this.form.level = this.form.parentId != null ? 2 : 1;
          if (this.form.id != null) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.id ? [row.id] : this.ids).map(id => ({id}));
      console.log(ids)
      this.$modal.confirm(this.$t('delete-or-not')).then(function () {
        return delCategory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('delete-success'));
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('good/category/export', {
        ...this.queryParams
      }, `category_${new Date().getTime()}.xlsx`)
    },
    //启用禁用
    enableChange(id) {
      enable(id).then(res => {
        if(res){
          this.$modal.msgSuccess("修改成功");
          this.getList();
        }
      })

    },
  }
};
</script>
